const { ContentCategory } = require('../config/Sequelize')
const { CriteriaExample } = require('../utils/CriteriaExample')

/**
 * 查询文章分类
 * @param {*} category 
 * @returns 
 */
const selecCategoryList = async (category = {}) => {
  const categoryExample = new CriteriaExample(category)
  console.log(category)
  categoryExample.and()
    .like('name', category.name)
    .eq('status', category.status)
  // const deptExample = new CriteriaExample(category)
  const allCategorys = await ContentCategory.findAll({
    where: categoryExample.getWhere(),
    order: [['sort', 'ASC']],
  })

  // 构建树形结构
  const categoryTree = [];

  function buildNode(m) {
    const node = m.toJSON();
    const children = allCategorys.filter((category) => category.pid === node.categoryId);
    if (children.length > 0) {
      node.children = children.map((child) => buildNode(child));
    }
    return node;
  }

  // 查找根节点（假设根节点的 parent_id 为 0
  const rootNodes = allCategorys.filter((category) => category.pid === 0);

  rootNodes.forEach((rootNode) => {
    categoryTree.push(buildNode(rootNode));
  });

  return { total: categoryTree.length, data: categoryTree }
}

/**
 * 根据文章分类id查询文章分类信息
 * @param {*} id 
 * @returns 
 */
const selectCategoryById = async (id) => {
  console.log(id)
  const category = await ContentCategory.findOne({
    where: { categoryId: id },
    // include: [{
    //   model: SysDept, required: false,
    // }]
  })
  return category
}


/**
 * 添加文章分类信息
 * @param {*} category 
 * @returns 
 */
const addCategory = async (category) => {
  return ContentCategory.create(category)
}

/**
 * 更新文章分类信息
 * @param {*} category 
 * @returns 
 */
const updateCategory = async (category) => {
  return ContentCategory.update(category, {
    where: {
      categoryId: category.categoryId
    }
  })
}

/**
 * 删除文章分类信息
 * @param {*} category 
 * @returns 
 */
const deleteCategory = async (id) => {
  return ContentCategory.destroy({
    where: { categoryId: id }
  })
}

module.exports = {
  selecCategoryList,
  addCategory,
  updateCategory,
  deleteCategory,
  selectCategoryById
}